package edu.hit.crawler;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;

import edu.hit.crawler.io.CrawItem;
import edu.hit.crawler.util.URLFilter;

/**
 * merge seed urls into db.
 */
@SuppressWarnings("deprecation")
public class DbMergerDriver extends Configured implements Tool {

	public static Logger logger = Logger.getLogger(DbMergerDriver.class);

	

	public static class DbMergeMappder extends
			Mapper<Text, CrawItem, Text, CrawItem> {
		@Override
		protected void map(
				Text key,
				CrawItem value,
				org.apache.hadoop.mapreduce.Mapper<Text, CrawItem, Text, CrawItem>.Context context)
				throws IOException, InterruptedException {
			if (null == key || 0 == key.getLength())
				return;
			if (!URLFilter.filter(key.toString())) {
				return;
			}
			context.write(key, value);
		};

	}

	public static class DbMergeReducer extends
			Reducer<Text, CrawItem, Text, CrawItem> {
		@Override
		protected void reduce(
				Text key,
				java.lang.Iterable<CrawItem> values,
				org.apache.hadoop.mapreduce.Reducer<Text, CrawItem, Text, CrawItem>.Context context)
				throws IOException, InterruptedException {

			for (CrawItem value : values) {
				System.out.println(key.toString());
				context.write(key, value);
			}
		};
	}

	public static void main(String[] args) throws Exception {

		int res = ToolRunner.run(new Configuration(), new DbMergerDriver(), args);
		System.exit(res);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.hadoop.util.Tool#run(java.lang.String[])
	 */
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.hadoop.util.Tool#run(java.lang.String[])
	 */
	@Override
	public int run(String[] args) throws Exception {
		// configure a job and start it
		Configuration conf = getConf();
		Job job = new Job(conf, "Inject");
		job.setJarByClass(Crawler.class);
		job.setMapperClass(DbMergeMappder.class);
		job.setReducerClass(DbMergeReducer.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(CrawItem.class);
		
		job.setInputFormatClass(SequenceFileInputFormat.class);
		job.setOutputFormatClass(MapFileOutputFormat.class);
		job.setNumReduceTasks(2);

		String workdir = conf.get("org.work.crawler.dir", "crawler/");
		FileInputFormat.addInputPath(job, new Path(workdir + "crawl_db_new/"));
		FileInputFormat.addInputPath(job, new Path(workdir + "crawl_db/"));
		Path out = new Path(workdir + "crawl_db_tmp/");

		MapFileOutputFormat.setOutputPath(job, out);

		int res = job.waitForCompletion(true) ? 0 : 1;

		if (res == 0) {
			System.out.println("DbMerge done!");
			FileSystem fs = FileSystem.get(conf);
			fs.delete(new Path(workdir + "crawl_db"), true);
			fs.delete(new Path(workdir + "crawl_db_new"), true);
			fs.rename(out, new Path(workdir + "crawl_db"));
			
		} else {
			System.out.println("DbMerge failed.");
		}

		return res;
	}
}
